import { useState, useEffect } from "react";
import { Table, Button, Modal, Form, Input, Space, Tag, Select } from "antd";
import { message } from "../../utils/customMessage";
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import { http } from "../../utils/request";
import { API_ENDPOINTS } from "../../services/api";

interface RoleData {
  id: number;
  name: string;
  description: string;
  menuList: any[];
}

interface UserData {
  id: string;
  username: string;
  fullName: string;
  email: string;
  tel: string;
  role: RoleData;
  status: number;
}

interface TableParams {
  pagination: {
    current: number;
    pageSize: number;
  };
}

const UserManager = () => {
  const [data, setData] = useState<UserData[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 30,
    },
  });
  const [modalType, setModalType] = useState<"add" | "edit">("add");
  const [selectedUser, setSelectedUser] = useState<UserData | null>(null);
  const [roleList, setRoleList] = useState<RoleData[]>([]);

  // 获取角色列表 - 更新接口地址和数据处理
  const fetchRoleList = async () => {
    try {
      const result = await http.get("/api/role/page?pageNum=1&pageSize=100");
      if (+result.status === 200) {
        // 根据实际返回的数据结构处理
        const roleData = Array.isArray(result.data)
          ? result.data
          : result.data?.records || [];
        setRoleList(roleData);
      }
    } catch (error) {
      console.error("获取角色列表失败:", error);
      message.error("获取角色列表失败");
    }
  };

  // 获取用户列表
  const fetchData = async () => {
    setLoading(true);
    try {
      const result = await http.get(
        `${API_ENDPOINTS.USER_LIST}?page=${tableParams.pagination.current}&pageSize=${tableParams.pagination.pageSize}`
      );

      setData(result.data);
      setTableParams({
        ...tableParams,
        pagination: {
          ...tableParams.pagination,
          total: result.total,
        },
      });
    } catch (error) {
      message.error("获取用户列表失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    fetchRoleList(); // 初始化时获取角色列表
  }, [tableParams.pagination.current, tableParams.pagination.pageSize]);

  // 表格列定义
  const columns: ColumnsType<UserData> = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: 80,
    },
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
      width: 120,
    },
    {
      title: "姓名",
      dataIndex: "fullName",
      key: "fullName",
      width: 120,
    },
    {
      title: "密码",
      dataIndex: "password",
      key: "password",
      width: 100,
      render: () => "******", // 隐私保护，不显示实际密码
    },
    {
      title: "电话",
      dataIndex: "tel",
      key: "tel",
      width: 130,
    },
    {
      title: "角色",
      dataIndex: "role",
      key: "role",
      width: 150,
      render: (role: RoleData) => {
        if (!role) return <Tag color="default">未分配</Tag>;

        // 根据角色名称设置不同颜色
        const getRoleColor = (name: string) => {
          if (name.includes("管理员")) return "red";
          if (name.includes("操作员")) return "blue";
          if (name.includes("用户")) return "green";
          return "default";
        };

        return (
          <Tag color={getRoleColor(role.name)} title={role.description}>
            {role.name}
          </Tag>
        );
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 100,
      render: (status: number) => {
        const statusMap = {
          0: { text: "正常", color: "success" },
          1: { text: "锁定", color: "warning" },
          2: { text: "禁用", color: "error" },
        };
        const { text, color } = statusMap[status] || {
          text: "未知",
          color: "default",
        };
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: "操作",
      key: "action",
      width: 150,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 处理表格变化
  const handleTableChange = (pagination: any) => {
    setTableParams({
      ...tableParams,
      pagination,
    });
  };

  // 修改编辑按钮的处理函数
  const handleEdit = (record: UserData) => {
    setModalType("edit");
    setSelectedUser(record);

    // 设置表单值，特别处理角色字段
    const formValues = {
      ...record,
      roleId: record.role?.id, // 将角色对象转换为角色ID用于表单显示
    };

    form.setFieldsValue(formValues);
    setIsModalVisible(true);
  };

  // 修改更新用户的处理函数
  const handleUpdate = async (values: any) => {
    try {
      // 将 roleId 转换为 role 对象格式
      const updateData = {
        ...values,
        id: selectedUser?.id,
        role: {
          id: values.roleId,
        },
      };

      // 删除 roleId 字段，避免冗余
      delete updateData.roleId;

      const result = await http.post(API_ENDPOINTS.USER_UPDATE, updateData);

      if (+result.status === 200) {
        message.success("更新用户成功");
        setIsModalVisible(false);
        form.resetFields();
        fetchData();
      } else {
        message.error(result.message || "更新用户失败");
      }
    } catch (error) {
      message.error("更新用户失败");
    }
  };

  // 修改 Modal 的确认按钮处理函数
  const handleModalOk = () => {
    form.validateFields().then((values) => {
      if (modalType === "add") {
        handleAdd(values);
      } else {
        handleUpdate(values);
      }
    });
  };

  // 处理新增
  const handleAdd = async (values: any) => {
    try {
      // 将 roleId 转换为 role 对象格式
      const saveData = {
        ...values,
        role: {
          id: values.roleId,
        },
      };

      // 删除 roleId 字段，避免冗余
      delete saveData.roleId;

      await http.post("/api/user/save", saveData);
      message.success("添加成功");
      setIsModalVisible(false);
      form.resetFields();
      fetchData(); // 刷新数据
    } catch (error) {
      message.error("操作失败");
    }
  };

  // 处理删除
  const handleDelete = async (id: string) => {
    try {
      await http.post(`/api/user/del`, { id });
      message.success("删除成功");
      fetchData(); // 刷新数据
    } catch (error) {
      message.error("删除失败");
    }
  };

  return (
    <div style={{ padding: "20px" }}>
      <div style={{ marginBottom: "16px" }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            setModalType("add");
            form.resetFields();
            setIsModalVisible(true);
          }}
        >
          新增用户
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        pagination={tableParams.pagination}
        loading={loading}
        onChange={handleTableChange}
        scroll={{ x: 1000 }}
      />

      <Modal
        title={modalType === "add" ? "新增用户" : "编辑用户"}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
        }}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            name="fullName"
            label="姓名"
            rules={[{ required: true, message: "请输入姓名" }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>

          <Form.Item
            name="tel"
            label="电话"
            rules={[{ required: true, message: "请输入电话" }]}
          >
            <Input placeholder="请输入电话" />
          </Form.Item>

          <Form.Item
            name="roleId"
            label="角色"
            rules={[{ required: true, message: "请选择角色" }]}
          >
            <Select
              placeholder="请选择角色"
              allowClear
              showSearch
              filterOption={(input, option) =>
                (option?.children as any)?.props?.children?.[0]?.props?.children
                  ?.toLowerCase()
                  ?.includes(input.toLowerCase()) ||
                (option?.children as any)?.props?.children?.[1]?.props?.children
                  ?.toLowerCase()
                  ?.includes(input.toLowerCase())
              }
            >
              {roleList.map((role) => (
                <Select.Option key={role.id} value={role.id}>
                  <div style={{ padding: "4px 0" }}>
                    <div style={{ fontWeight: "500", marginBottom: "2px" }}>
                      {role.name}
                    </div>
                    {role.description && (
                      <div
                        style={{
                          fontSize: "12px",
                          color: "#666",
                          lineHeight: "1.2",
                        }}
                      >
                        {role.description}
                      </div>
                    )}
                    <div
                      style={{
                        fontSize: "11px",
                        color: "#999",
                        marginTop: "2px",
                      }}
                    >
                      权限菜单: {role.menuList?.length || 0} 个
                    </div>
                  </div>
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: "请选择状态" }]}
          >
            <Select placeholder="请选择状态">
              <Select.Option value={0}>
                <Tag color="success">正常</Tag>
              </Select.Option>
              <Select.Option value={1}>
                <Tag color="warning">锁定</Tag>
              </Select.Option>
              <Select.Option value={2}>
                <Tag color="error">禁用</Tag>
              </Select.Option>
            </Select>
          </Form.Item>

          {modalType === "add" && (
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: "请输入密码" }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default UserManager;
